<?php

declare(strict_types=1);

namespace app\api\controller\user;

use app\BaseController;
use think\facade\Validate;

use app\common\model\User\User as UserModel;
use app\common\model\User\Address as AddressModel;
use app\common\model\Region as RegionModel;
use app\common\validate\User\Address as AddressValidate;
use think\exception\ValidateException;

class Address extends BaseController
{

    public function initialize()
    {
        parent::initialize();

        $this->UserModel = new UserModel();
        $this->AddressModel = new AddressModel();
        $this->RegionModel = new RegionModel();
    }


    // 收货地址列表
    public function index()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', '');

            $userinfo = $this->UserModel->find($userid);

            if (!$userinfo) {
                $this->error('用户不存在');
                exit;
            }

            $result = $this->AddressModel->with(['provinces', 'citys', 'districts'])->where(['userid' => $userid])->select();

            $this->success('返回收货地址成功', null, $result);
            exit;
        }
    }

    //切换默认收货地址
    public function check()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', 0);

            $addrid = $this->request->param('addrid', 0);

            //先判断这个人是否存在
            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $address = $this->AddressModel->find($addrid);

            if (!$address) {
                $this->error('收货地址不存在');
                exit;
            }

            if ($address['userid'] != $userid) {
                $this->error('非法修改他人地址，无权修改');
                exit;
            }

            //先把这个人的所有的收货地址都改成0 非默认 ，在改指定这个id地址

            //开启事务
            $this->AddressModel->startTrans();

            $UpdateStatus = $this->AddressModel->where(['userid' => $userid])->update(['status' => 0]);


            if ($UpdateStatus === FALSE) {
                $this->error('更新默认收货地址失败');
                exit;
            }

            //更新选中的地址
            $result = $this->AddressModel->where(['id' => $addrid])->update(['status' => 1]);

            if ($result === FALSE) {
                //回滚事务
                $this->AddressModel->rollback();
                $this->error('更新默认地址失败');
                exit;
            } else {
                //提交事务
                $this->AddressModel->commit();
                $this->success('更新默认地址成功');
                exit;
            }
        }
    }


    //新增收货地址
    public function add()
    {
        if ($this->request->isPost()) {

            $params = $this->request->param();

            //获取用户id 判断用户是否存在
            $userid = $this->request->param('userid', 0);
            $code = $this->request->param('code', 0);

            $user = $this->UserModel->find($userid);
            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            //组装数据
            $data = [
                'consignee' => $params['consignee'],
                'mobile' => $params['mobile'],
                'address' => $params['address'],
                'status' => $params['status'],
                'userid' => $params['userid'],
            ];

            //查询地区数据
            $parentpath = $this->RegionModel->where(['code' =>  $code])->value('parentpath');

            if (empty($parentpath)) {
                $this->error('您所选择的地区不存在,请重新选择');
                exit;
            }

            //将字符串转换为数组
            $path = explode(',', $parentpath);

            if (count($path) <= 0) {
                $this->error('您所选择的地区不存在,请重新选择');
                exit;
            }

            //将数组里面的值分别给到不同的变量
            list($data['province'], $data['city'], $data['district']) = $path;

            //判断是否选择了默认地址
            if ($data['status'] == 1) {
                //将这个人所有的收货地址都要改成非默认
                $UpdateStatus = $this->AddressModel->where(['userid' => $userid])->update(['status' => 0]);

                if ($UpdateStatus === FALSE) {
                    $this->error('更新默认收货地址失败');
                    exit;
                }
            }


            try {
                validate(AddressValidate::class)->check($data);
                //开始插入数据库 validate('common/User/User')
                $result = $this->AddressModel->save($data);
            } catch (ValidateException $e) {
                // 捕获异常
                $this->error($e->getError());
                exit;
            }


            if ($result === FALSE) {
                $this->error($this->AddressModel->getError());
                exit;
            } else {
                $this->success('添加收货地址成功');
                exit;
            }
        }
    }

    //查询地址详情
    public function info()
    {
        if ($this->request->isPost()) {

            $id = $this->request->param('id', 0);
            $userid = $this->request->param('userid', 0);

            //获取用户id 判断用户是否存在
            $user = $this->UserModel->find($userid);
            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $info = $this->AddressModel->with(['provinces', 'citys', 'districts'])->find($id);

            if ($info === FALSE) {
                $this->error($this->AddressModel->getError());
                exit;
            } else {
                $this->success('', null, $info);
                exit;
            }
            exit;
        }
    }

    //编辑收货地址
    public function update()
    {
        if ($this->request->isPost()) {

            $params = $this->request->param();

            $userid = $this->request->param('userid', 0);
            $code = $this->request->param('code', 0);

            //获取用户id 判断用户是否存在
            $user = $this->UserModel->find($userid);
            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            //组装数据
            $data = [
                'id' => $params['id'],
                'consignee' => $params['consignee'],
                'mobile' => $params['mobile'],
                'address' => $params['address'],
                'status' => $params['status'],
                'userid' => $params['userid'],
            ];

            //查询地区数据
            $parentpath = $this->RegionModel->where(['code' =>  $code])->value('parentpath');

            if (empty($parentpath)) {
                $this->error('您所选择的地区不存在,请重新选择');
                exit;
            }

            //将字符串转换为数组
            $path = explode(',', $parentpath);

            if (count($path) <= 0) {
                $this->error('您所选择的地区不存在,请重新选择');
                exit;
            }

            //将数组里面的值分别给到不同的变量
            list($data['province'], $data['city'], $data['district']) = $path;


            //判断是否选择了默认地址
            if ($data['status'] == 1) {
                //将这个人所有的收货地址都要改成非默认
                $UpdateStatus = $this->AddressModel->where(['userid' => $userid])->update(['status' => 0]);

                if ($UpdateStatus === FALSE) {
                    $this->error('更新默认收货地址失败');
                    exit;
                }
            }

            try {
                validate(AddressValidate::class)->check($data);
                //开始插入数据库 validate('common/User/User')
                $result = $this->AddressModel->update($data);
            } catch (ValidateException $e) {
                // 捕获异常
                $this->error($e->getError());
                exit;
            }

            if ($result === FALSE) {
                $this->error($this->AddressModel->getError());
                exit;
            } else {
                $this->success('修改收货地址成功');
                exit;
            }
        }
    }

    // 删除收货地址
    public function delete()
    {
        if ($this->request->isPost()) {

            $id = $this->request->param('id', 0);
            $userid = $this->request->param('userid', 0);


            //获取用户id 判断用户是否存在
            $user = $this->UserModel->find($userid);
            if (!$user) {
                $this->error('用户不存在');
                exit;
            }


            $result = $this->AddressModel->destroy(['id' => $id]);

            if ($result === FALSE) {
                $this->error($this->AddressModel->getError());
                exit;
            } else {
                $this->success('删除成功');
                exit;
            }
        }
    }

    // 获取默认地址
    public function order()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', 0);

            //获取用户id 判断用户是否存在
            $user = $this->UserModel->find($userid);
            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $where = [
                'userid' => $userid,
                'status' => 1
            ];
            //查找这个人的默认收货地址
            $info = $this->AddressModel->with(['provinces', 'citys', 'districts'])->where($where)->find();

            if ($info) {
                $this->success('返回默认收货地址', null, $info);
                exit;
            }

            //如果没有默认的收货地址，就随便找一条给他
            $address = $this->AddressModel->with(['provinces', 'citys', 'districts'])->where(['userid' => $userid])->find();

            if (!$address) {
                $this->error('暂无收货地址');
                exit;
            }

            $this->success('返回默认收货地址', null, $address);
            exit;
        }
    }
}
